package logic

import (
	"context"
	"fmt"
	"info-hub/model"
	"info-hub/pkg"
	"strconv"

	"info-hub/inforpc/inforpc"
	"info-hub/inforpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *inforpc.LoginRequest) (*inforpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user model.User
	model.DB.Where("account", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("用户未注册请注册")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	handler, err := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	if err != nil {
		return nil, err
	}
	atoi, err := strconv.Atoi(handler)
	if err != nil {
		return nil, err
	}
	return &inforpc.LoginResponse{
		UserId: int64(atoi),
	}, nil
}
